import {Component, OnInit} from '@angular/core';
import {AliyunOssOutputUrl} from "../../../../config/api";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {Observable} from "rxjs/Observable";
import {isInteger} from "@ng-bootstrap/ng-bootstrap/util/util";
import {ActivatedRoute, Router} from "@angular/router";
import {DisplayService} from "../display.service";
import {GroupService} from "../../group/group.service";
import {NzMessageService} from 'ng-zorro-antd';
import {AdOssUploadService} from "../../../lib/service/ad-oss-upload.service";
import {LocalStorageService} from "../../../lib/service/local-storage.service";


@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss'],
  providers: [NzMessageService, GroupService]
})
export class EditComponent implements OnInit {


  validateForm: FormGroup;
  fileList = [];
  picList = [];
  options = [];
  showCaseId;
  id;
  boothNumber;
  loadingInfo: boolean;
  name: string;
  types = 0;
  stage = 2;
  status1 = 1;

  aliyunOssOutputUrl = AliyunOssOutputUrl;

  picSizeInfo;

  submitStatus = false;

  //右侧预览区块
  previewTitle;
  previewsubTitle;
  previewSrc;
  page = 1;
  pageSize = 5;


  /* 商品弹窗 */
  goodsModalVisible = false;
  goodsList = [];
  groupList = [];
  selectedGroup;
  keyword;
  currentClickGoods = {};
  checkedGoodsInfo = {};
  total;
  status = '上架';
  loading = false;
  currentGoodsPrice = 0;
  comparePriceStatus = false;
  skuStatus = false;
  highPriceSkuId = null;
  ghostData = null;
  randomStatus = false;
  activity_goods_prize;


  //活动弹窗
  activityModalVisible = false;
  activityList = [];
  activityLoading = false;
  activitiesTotal;
  currentClickActivity = {};
  checkedActivityInfo = {};
  activityClickIndex;
  self = this;


  //卡券弹窗
  couponModalVisible = false;
  couponList = [];
  couponLoading = false;
  couponsTotal;
  currentClickCoupon = {};
  checkedCouponInfo = {};
  couponKeyWord = '';
  couponClickIndex;
  showcase_id;
  selectedOption;

  typesArr = {
    product: this.getGoodsList.bind(this.self),
    coupons: this.getCouponList.bind(this.self),
    activity: this.getActivityList.bind(this.self),
    picture: this.getActivityList.bind(this.self)
  };
  typeText = {
    1: {text: '普通拼团', color: 'rgb(299,112,23)'},
    2: {text: '拉新拼团', color: 'rgb(299,112,23)'},
    3: {text: '抽奖拼团', color: 'rgb(299,112,23)'},
    4: {text: '团长免单', color: 'rgb(299,112,23)'},
  };

  clearOtherList = {
    product: ['currentClickGoods', 'checkedGoodsInfo'],
    coupons: ['currentClickCoupon', 'checkedCouponInfo'],
    activity: ['currentClickActivity', 'checkedActivityInfo'],
    picture: ['currentClickActivity', 'checkedActivityInfo']
  };

  urlReg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;

  type = '';

  f1 = ['showcaseDetail'];

  template_id;

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  // 整数验证
  integerValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (!isInteger(control.value)) {
        observer.next({error: true, notInteger: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  }
  //价格验证
  priceValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value > this.currentGoodsPrice) {
        observer.next({error: true, priceToHigh: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    })
  };
  //url验证
  urlValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value == '' || control.value == null) {
        observer.next(null);
      } else if (!this.urlReg.test(control.value)) {
        observer.next({error: true, urlError: true});
      } else {
        observer.next(null);
      }
      observer.complete();

    })
  };


  constructor(private routeInfo: ActivatedRoute,
              public displayService: DisplayService,
              private fb: FormBuilder,
              private groupService: GroupService,
              private _message: NzMessageService,
              private router: Router,
              private adOssUploadService: AdOssUploadService,
              private localStorageService: LocalStorageService,
  ) {
    this.validateForm = this.fb.group({
      'name': ['', [Validators.required]],
      'showcase_id': ['', [Validators.required]],
      'type': ['', Validators.required],
      'sort': ['', [Validators.required, Validators.min(0), Validators.max(99)], this.integerValidators],
      'url': [''],
      'relationID': ['']
    })

  }

  ngOnInit() {
    this.template_id = this.localStorageService.getNowApplet()['template_id'];
    this.routeInfo.params.subscribe(params => {
      this.page = 1;
      this.pageSize = 5;
      this.showCaseId = params.showcaseId;
      this.boothNumber = params.boothNumber;
      this.id = params.id;
      this.currentClickCoupon = {};
      this.currentClickActivity = {};
      this.currentClickGoods = {};
      this.checkedCouponInfo = {};
      this.checkedActivityInfo = {};
      this.checkedGoodsInfo = {};
      this.couponModalVisible = false;
      this.activityModalVisible = false;
      this.goodsModalVisible = false;
      this.activityList = [];
      this.goodsList = [];
      this.couponList = [];
      this.fileList = [];
      this.picList = [];
      this.previewTitle = '';
      this.previewsubTitle = '';
      this.previewSrc = '';
      this.type = '';


      if (this.displayService.list.length == 0) {
        this.getShowCaseList().then(() => {
          this.displayService.list.map((e, i) => {
            if (e['booth_number'] == this.boothNumber) {
              e['typeOpen'] = true;
              this.displayService.id = this.id;
              this.displayService.name = e['name'];
              this.displayService.showCaseId = e['id'];
              this.displayService.boothNumber = this.boothNumber;
            }
          });
        });
      }

      this.validateForm.controls['name'].setValue('');
      this.validateForm.controls['relationID'].setValue('');
      this.validateForm.controls['showcase_id'].setValue('');
      this.validateForm.controls['sort'].setValue('');
      this.getShowCaseDetailInfo(params.id, params.boothNumber);
    })

  }

  getShowCaseList() {
    return new Promise((resolve, reject) => {
      this.displayService.getShowCaseList(this.template_id).subscribe(res => {
        if (res.code === 2000) {
          this.displayService.list = res.data.data;
          let len = this.displayService.list.length;
          this.displayService.list.map((e, i) => {
            e['typeOpen'] = false;
            e['addShow'] = false;
            e['typeValue'] = '';
            this.displayService.getShowCaseDetailList(e['id']).subscribe(res1 => {
              if (res.code === 2000) {
                len--;
                let detailList = this.displayService.list[i]['detailList'] = res1.data.data;
                detailList.map((e, i) => {
                  e['edit'] = false;
                });
                if (len === 0) {
                  resolve();
                }
              };
            });
          });
        }
      })
    })
  }


  getShowCaseDetailInfo(id, boothNumber) {
    this.loadingInfo = true;
    this.displayService.getShowCaseDetailInfo(id).subscribe(res => {
      if (res.code === 2000) {
        let data = res.data;
        this.displayService.initInfo(this, boothNumber);

        //  a 图片 产品 页面 卡券 活动
        // b 产品 页面 卡券 活动
        //c 图片

        if(boothNumber === 'b' && data.type === 'picture' || boothNumber === 'c' && data.type !== 'picture') {
          this.selectedOption = this.options[0];
          this.type = this.selectedOption.value;
          this.validateForm.controls['relationID'].setValue('');
          this.validateForm.controls['type'].setValue(this.type);
          console.log('1:' + this.validateForm.controls['type'].value);
          this.loadingInfo = false;
        } else if (data.type === 'picture') {
          this.type = data.type;
          this.validateForm.controls['type'].setValue(data.type);
          this.validateForm.controls['relationID'].setValue('');
          this.loadingSwitchData(data);
        } else {
          this.type = data.type;
          this.validateForm.controls['relationID'].setValue(data.relationID);
          this.validateForm.controls['type'].setValue(data.type);
          this.loadingSwitchData(data);
        }


        // if (boothNumber === 'b') {
        //   if (data.type === 'page') {
        //     this.type = 'picture';
        //     this.validateForm.controls['relationID'].setValue('');
        //     this.validateForm.controls['type'].setValue('picture');
        //     this.selectedOption = this.options[0];
        //     this.loadingInfo = false;
        //   } else {
        //     this.type = data.type;
        //     this.validateForm.controls['type'].setValue(data.type);
        //     this.validateForm.controls['relationID'].setValue(data.relationID);
        //     this.loadingSwitchData(data);
        //   }
        // } else if (boothNumber === 'c'){
        //   if (data.type == 'product' || data.type == 'coupons' || data.type == 'page') {
        //     this.validateForm.controls['relationID'].setValue('');
        //     this.loadingInfo = false;
        //   } else if (data.type === 'picture' || data.type === 'activity') {
        //     this.validateForm.controls['relationID'].setValue(data.relationID);
        //     if (data['activity']) {
        //     this.loadingSwitchData(data);
        //   } else {
        //     this.loadingInfo = false;
        //   }
        // }
        //   this.type = 'picture';
        //   this.validateForm.controls['type'].setValue('picture');
        // } else {
        //   this.type = data.type;
        //   this.options.map((e,i) => {
        //     if(e.value === this.type) {
        //       this.selectedOption = e;
        //     }
        //   });
        //   this.validateForm.controls['type'].setValue(data.type);
        //   this.loadingSwitchData(data);
        // }
        this.validateForm.controls['name'].setValue(data.name);
        this.validateForm.controls['sort'].setValue(data.sort);
        this.validateForm.controls['url'].setValue(data.url);
        this.validateForm.controls['showcase_id'].setValue(data.showcase_id);
        if (data.image) {
          this.picList.push({src: `${AliyunOssOutputUrl}/${data.image}?update=${Date.now()}`});
        }
      }
    })
  }


  //根据type去获取请求对应的列表
  switchTypeList(type) {
    return this.typesArr[type];
  }

  //loadingSwitch
  loadingSwitchData(data) {
    this.pageSize = 100;
    this.options.map((e) => {
      if (e.value === data.type) {
        this.selectedOption = e;
        switch (data.type) {
          case 'product':
            console.log(data.relationID);
            if(data.relationID) {
              this.getGoodsList().then(() => {
                this.goodsList.map((e, i) => {
                  if (e.id == data.relationID) {
                    this.checkedGoodsInfo = this.currentClickGoods = e;
                    this.loadingInfo = false;
                    this.pageSize = 5;
                  }
                })
              }).catch((res) => {
                this.loadingInfo = false;
              });
            } else {
              this.loadingInfo = false;
            }
            break;
          case 'picture':
            this.getActivityList().then(() => {
              this.getActivityInfo(data);
            }).catch((res) => {
              this.loadingInfo = false;
            });
            break;
          case 'activity':
            this.getActivityList().then(() => {
              this.getActivityInfo(data);
            }).catch((res) => {
              this.loadingInfo = false;
            });
            ;
            break;
          case 'coupons':
            this.getCouponList().then(() => {
              this.couponList.map((e, i) => {
                if (e.card_coupons_uuid == data.relationID) {
                  this.checkedCouponInfo = this.currentClickCoupon = e;
                  this.loadingInfo = false;
                  this.pageSize = 5;
                }
              })
            }).catch((res) => {
              this.loadingInfo = false;
            });
            break;
          default:
            this.loadingInfo = false;
        }
      }
    });
  }


  getActivityInfo(data) {
    let activity = data['activity'];
    let goods = activity['activity_goods'][0];
    this.checkedActivityInfo = activity;
    this.checkedActivityInfo['type'] = this.typeText[goods['type']];
    this.checkedActivityInfo['goodsDetail'] = goods['goods'];
    this.loadingInfo = false;
    this.pageSize = 5;
  }

  //切换选择类型
  checkType(e) {
    if (!e) {
      let controlValue = this.validateForm.controls['type'].value;
      let selectedValue = this.selectedOption.value;
      if (controlValue !== selectedValue) {
        this.validateForm.controls['type'].setValue(selectedValue);
        this.validateForm.controls['relationID'].setValue('');
        this.type = selectedValue;
        for (let k in this.clearOtherList) {
          if (k !== selectedValue) {
            this.clearOtherList[k].map((e, i) => {
              this[e] = {};
            })
          }
        }
      }
      if(selectedValue != 'page') {
        this.validateForm.controls['url'].setValue('');
      }
    }
  }


  /* 商品弹窗逻辑 */

  // 获取商品列表
  getGoodsList() {
    this.loading = true;
    this.getGroupList();
    return new Promise((resolve, reject) => {
      this.groupService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.keyword, this.status).subscribe(res => {
        if (res.code === 2000) {
          this.total = res.data.total;
          const goodsList = res.data.data;
          const goodsId = [];
          goodsList.forEach(item => {
            goodsId.push(item.id);
          });
          this.groupService.getbindListAll('[' + goodsId.join(',') + ']').subscribe(rs => {
            if (rs.code === 2000) {
              const goodsjson = {};
              rs.data.forEach(item => {
                if (!goodsjson[item.goods_id]) {
                  goodsjson[item.goods_id] = [item.name];
                } else {
                  goodsjson[item.goods_id].push(item.name);
                }
              });
              goodsList.forEach(item => {
                if (item.goods_number) {
                  item.goods_number = item.goods_number.split('|');
                }
                item.goods_category = goodsjson[item.id];
              });
            }
            this.goodsList = goodsList;
            resolve(this.goodsList);
            this.loading = false;
          });
        } else {
          this._message.create('error', res.message);
        }
        this.loading = false;
      });
    })
  }

  // 获取店铺商品类型列表
  getGroupList() {
    this.groupService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
    });
  }

  // 搜索商品
  searchGoods() {
    this.page = 1;
    this.getGoodsList();
  }

  // 添加商品
  addGoods() {
    this.currentClickGoods = JSON.parse(JSON.stringify(this.currentClickGoods));
    this.goodsModalVisible = true;
    this.page = 1;
    this.pageSize = 5;
    this.keyword = '';
    this.switchTypeList(this.selectedOption.value)();
  }

  // 关闭添加商品弹窗
  closeModal() {
    this.currentClickGoods = JSON.parse(JSON.stringify(this.checkedGoodsInfo));
    this.goodsModalVisible = false;
  }

  // 确认选择商品
  confirmCheckedGoods() {
    if (!Object.keys(this.currentClickGoods).length) {
      this._message.create('error', '请选择商品');
      return;
    }
    this.checkedGoodsInfo = JSON.parse(JSON.stringify(this.currentClickGoods));
    this.validateForm.controls['relationID'].setValue(this.checkedGoodsInfo['id'] + '');
    this.groupService.getGoodsSkuList(this.currentClickGoods['id'], 100).subscribe(res => {
      if (res.code === 2000) {
        const sku = res.data.data;
        const activity_goods_prize = [];
        sku.map((val, idx) => {
          val.checked = true;
          const sku_item = {'sku_id': val.id, 'number': val.in_stock};
          activity_goods_prize.push(sku_item);
        });
        this.activity_goods_prize = activity_goods_prize;
        this.checkedGoodsInfo['sku'] = sku;
        this.goodsModalVisible = false;
      } else {
        this._message.create('error', res.message);
      }
    });
  }


  /*活动弹窗逻辑*/

  // 获取活动列表
  getActivityList() {
    this.activityLoading = true;
    return new Promise((resolve, reject) => {
      this.displayService.getActivityList(this.page, this.pageSize, this.keyword, this.types, this.stage, this.status1).subscribe(res => {
        if (res.code === 2000) {
          this.activityList = res.data.data;
          this.activityList.map((e, i) => {
            e['flexable'] = false;
          });
          this.activitiesTotal = res.data.total;
          this.activityLoading = false;
          resolve();
        }
      })

    })
  }

  //搜索活动
  searchActivity() {
    this.page = 1;
    this.getActivityList();
  }

  //打开活动模态框
  addActivity() {
    this.currentClickActivity = this.checkedActivityInfo;
    this.activityModalVisible = true;
    this.page = 1;
    this.pageSize = 5;
    this.keyword = '';
    this.switchTypeList(this.selectedOption.value)();
  }

  //关闭活动模态框
  closeActivityModal() {
    this.activityModalVisible = false;
    this.activityList.map((e, i) => {
      e['flexable'] = false;
    });
  }

  //确认活动模态框
  confirmCheckedActivity() {
    this.checkedActivityInfo = this.currentClickActivity;
    this.checkedActivityInfo['flexable'] = false;
    this.checkedActivityInfo['type'] = this.typeText[this.currentClickActivity['activity_goods'][0]['type']];
    this.validateForm.controls['relationID'].setValue(this.checkedActivityInfo['id'] + '');
    this.activityList.map((e, i) => {
      e['flexable'] = false;
    });
    this.activityModalVisible = false;
  }

  //获取活动商品列表
  getActivityGoodsList(activityId, activityGoodsId) {
    this.displayService.getActivityGoodsList(activityId, activityGoodsId).subscribe(res => {
      if (res.code === 2000) {
        this.activityList[this.activityClickIndex]['goodsDetail'] = res.data;
      }
    })
  }

  //查看活动商品
  toggleFlexable(i) {
    this.activityClickIndex = i;
    let target = this.activityList[i];
    target['flexable'] = !target['flexable'];
    if (target['flexable']) {
      let activityId = target['id'], activity_goods_id = target['activity_goods'][0]['id'];
      this.getActivityGoodsList(activityId, activity_goods_id);
    }
  }

  //切换checked查看商品
  toggleViewActivityGoods() {
    this.checkedActivityInfo['flexable'] = !this.checkedActivityInfo['flexable'];
  }


  /*卡券弹窗逻辑*/
  addCoupon() {
    this.couponModalVisible = true;
    this.page = 1;
    this.pageSize = 5;
    this.keyword = '';
    this.switchTypeList(this.selectedOption.value)();
  }

  //获取卡券列表
  getCouponList() {
    return new Promise((resolve, reject) => {
      this.displayService.getCouponList(this.page, this.pageSize, this.keyword).subscribe(res => {
        if (res.code === 2000) {
          this.couponList = res.data.data;
          this.couponsTotal = res.data.total;
          resolve();
        }
      });
    });
  }

  //搜索卡券
  searchCoupon() {
    this.page = 1;
    this.switchTypeList(this.selectedOption.value)();
    // this.getCouponList();
  }

  //关闭卡券模态框
  closeCouponModal() {
    this.couponModalVisible = false;
    this.currentClickCoupon = this.checkedCouponInfo;
  }

  //确认卡券模态框信息
  confirmCheckedCoupon() {
    this.checkedCouponInfo = this.currentClickCoupon;
    this.validateForm.controls['relationID'].setValue(this.checkedCouponInfo['card_coupons_uuid'] + '');
    this.couponModalVisible = false;
  }


  //重置
  reset() {
    this.keyword = '';
    this.page = 1;
    this.pageSize = 5;
    this.switchTypeList(this.selectedOption.value)();
  }

  uploadImg(showcase_detail_id) {
    this.adOssUploadService
      .getSignature(`/v1/common/showcase_detail/${showcase_detail_id}?callback=true`)
      .subscribe(
        res1 => {
          let length = this.fileList.filter(item => {
            return item && item != "pic";
          }).length;
          let successLen = 0;
          if (length == 0) {
            this.submitStatus = false;
            this._message.create("success", '修改成功');
            this.router.navigate([`member/display/${this.showCaseId}/${showcase_detail_id}/${this.boothNumber}`]);
            return false;
          }
          this.fileList.every((val, idx, array) => {
            if (val && val != "pic") {
              this.adOssUploadService.fileUpload(val, res1.data, this.f1[idx] + '.' + val.name.replace(/.+\./, '').toLowerCase(), 'image')
                .subscribe(res2 => {
                    successLen++;
                    if (successLen == length) {
                      this.submitStatus = false;
                      this._message.create("success", '修改成功');
                      this.router.navigate([`member/display/${this.showCaseId}/${showcase_detail_id}/${this.boothNumber}`]);
                    }
                  }
                );
            }
            return true;
          });

        }
      );
  }

  picError = false;//图片是否错误
  fileChange() {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
  }


  currentClick(data) {
    this.currentClickActivity = data;
  }

  goBack() {
    this.router.navigate([`member/display/${this.showCaseId}/${this.id}/${this.boothNumber}`]);
  }

  _submitForm() {
      console.log(this.validateForm.value);
    if (this.submitStatus) {
      return;
    }
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    console.log(this.validateForm.value);
    if (this.validateForm.valid) {
      this.submitStatus = true;
      let data = this.validateForm.value;
      data['showcase_id'] = this.showCaseId;
      data['id'] = this.id;
      this.displayService.editShowCaseDetail(data).subscribe(res => {
        if (res.code === 2000) {
          this.submitStatus = false;
          this.uploadImg(this.id);
        } else {
          this.submitStatus = false;
          this._message.create('error', res.message);
        }
      });
    }
  }
}
